package com.cloud.school.app.config.security;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * SecurityUserUtils for Spring Security.
 */
@Slf4j
public final class SecurityUserUtils {

    public static final String LOGIN_USER = "loginUser.";

    public static Long getCurrentUserId() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal != null && principal instanceof SecurityUserDetails) {
                log.info("当前登录人:{}", JSON.toJSONString(principal));
                return ((SecurityUserDetails) principal).getUserId();
            }
        }
        log.error("当前登录人不存在！使用默认用户");
        return 239166808150118400l;
    }

    public static String getCurrentUserPhoneNum() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal != null && principal instanceof SecurityUserDetails) {
                return ((SecurityUserDetails) principal).getUsername();
            }
        }
        return "";
    }
}
